//
//  MultiSelectImageController.m
//  MultiSelectPhoto
//
//  Created by Burn on 2019/6/18.
//  Copyright © 2019 menksoft. All rights reserved.
//  多选照片控制器

#import "MultiSelectImageController.h"
#import "ImageCell.h"
#import "ImageModel.h"
#import <Photos/Photos.h>


@interface MultiSelectImageController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(strong,nonatomic) UICollectionView *collectionView;
@property(strong,nonatomic) NSMutableArray *choosImages;    //  已经选中的Image
@property(strong,nonatomic) NSMutableArray *dataSource;     //  数据源

@end

static NSString *const ID = @"CELLID";
NSInteger chooseSum = 2;
@implementation MultiSelectImageController

- (void)setImages:(NSArray *)images{
    [self.dataSource removeAllObjects];
    for (UIImage *image in images) {
        ImageModel *model = [[ImageModel alloc]init];
        model.image = image;
        model.choose = NO;
        [self.dataSource addObject:model];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.navTitle.length > 0 ? self.navTitle : @"所有照片";

    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ImageCell class]) bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:ID];
    [self.view addSubview:self.collectionView];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_nav_back_black"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    
    
    // 获得相机胶卷 All Photos(所有照片)
    if (!self.assetCollection) {
        PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
        [self enumerateAssetsInAssetCollection:cameraRoll original:YES];
    }else{
        [self enumerateAssetsInAssetCollection:self.assetCollection original:YES];
    }
    
    
}
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dismiss{
    
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"完成"]) {
        NSDictionary *info = [NSDictionary dictionaryWithObject:self.choosImages forKey:@"image"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"POSTIMAGE" object:nil userInfo:info];
        
        [self.choosImages removeAllObjects];
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.choosImages removeAllObjects];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    TViewController *vc = [[TViewController alloc]init];
//    vc.image = self.images[indexPath.item];
//    [self.navigationController pushViewController:vc animated:YES];
    
    
    
    ImageModel *model = self.dataSource[indexPath.item];
    model.choose = !model.isChoose;
    if (self.choosImages.count >= chooseSum && model.choose) {
        return;
    }
    
    if (model.choose) {
        [self.choosImages addObject:model.image];
    }else{
        [self.choosImages removeObject:model.image];
    }
    
    
    [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    
    
    if (self.choosImages.count > 0) {
        [self.navigationItem.rightBarButtonItem setTitle:@"完成"];
    }else{
        [self.navigationItem.rightBarButtonItem setTitle:@"取消"];
    }
    NSLog(@"%@",self.choosImages);
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.item];
    
    return cell;
}


- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = 2;
        layout.minimumInteritemSpacing = 2;
        layout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 6) / 4, ([UIScreen mainScreen].bounds.size.width - 6) / 4);
        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        
        _collectionView.dataSource = self;
    }
    return _collectionView;
}




- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
{
 
    static NSInteger count = 0;
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = NO;
    //    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    // 获得某个相簿中的所有PHAsset对象
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    NSLog(@"---------assets.count = %ld",assets.count);
    for (PHAsset *asset in assets) {
        // 是否要原图
        CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
        
        
        // 从asset中获得图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            
            NSLog(@"%@---%@",result,info);
            if (result) {
                ImageModel *model = [[ImageModel alloc]init];
                model.image = result;
                model.choose = NO;
                [self.dataSource addObject:model];
                [self.collectionView reloadData];
                count += 1;
                NSLog(@"-------%ld",count);
            }
        }];
    }
}



- (NSMutableArray *)choosImages{
    if (!_choosImages) {
        _choosImages = [NSMutableArray array];
    }
    return _choosImages;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

-(void)dealloc{
    NSLog(@"MultiSelectImageController - dealloc");
}


@end
